<template>
  <div class="app-container">
    <el-dialog
      :title="dialogtitle"
      :visible.sync="dialogVisible"
      width="98%"
      top="20px"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <Edit :infoid="id" :read-only="readonly" :timestamp="timestamp" @dialogHide="dialogHide($event)" />
    </el-dialog>

    <div class="filter-container">
      <el-select v-model="listQuery.sysDeptId" placeholder="请选择部门" clearable style="margin-left: 10px;width: 120px" class="filter-item">
        <el-option label="全公司" value="" />
        <el-option v-for="(it,index) in deptList" :key="index" :label="it.label" :value="it.value" />
      </el-select>
      <!-- <el-input v-model="listQuery.title" placeholder="请输入姓名" style="width: 200px;margin-left: 10px;" class="filter-item" /> -->
      <el-date-picker
        v-model="listQuery.year"
        align="right"
        unlink-panels
        placeholder="请选择年"
        style="margin-left: 10px;width:120px"
        class="filter-item"
        type="year"
        value-format="yyyy"
      />
      <el-select v-if="listQuery.year" v-model="listQuery.month" placeholder="选月" clearable style="margin-left: 10px;width: 90px" class="filter-item">
        <el-option label="全部" value="" />
        <el-option v-for="count in 12" :key="count" :label="count+'月'" :value="count" />
      </el-select>
      <el-button class="filter-item" type="primary" icon="el-icon-search" style="margin-left: 10px;" @click="handleFilter">
        搜索
      </el-button>
      <el-popconfirm title="确定批量删除所选信息吗？" style="margin-left:10px;float:right" @onConfirm="deleteData()">
        <el-button slot="reference" type="danger" class="filter-item" icon="el-icon-delete">批量删除</el-button>
      </el-popconfirm>
      <el-popconfirm title="确定批量发送信息吗？" style="margin-left:20px;float:right" @onConfirm="sendMessage()">
        <el-button slot="reference" type="primary" class="filter-item" icon="el-icon-s-comment">批量消息</el-button>
      </el-popconfirm>
      <el-popconfirm :title="'确定删除 '+importYear+'年'+(importMonth?importMonth+'月':'全年') +' 的信息吗？'" style="margin-left:10px;float:right" @onConfirm="deleteDataByMonth()">
        <el-button slot="reference" :disabled="!importYear" type="danger" class="filter-item" icon="el-icon-delete">删除</el-button>
      </el-popconfirm>
      <el-popconfirm :title="'确定给 '+importYear+'年'+(importMonth?importMonth+'月':'全年') +' 相关用户发信息吗？'" style="margin-left:10px;float:right" @onConfirm="sendMessageByMonth()">
        <el-button slot="reference" :disabled="!importYear||!importMonth" type="primary" class="filter-item" icon="el-icon-s-comment">发消息</el-button>
      </el-popconfirm>
      <el-upload
        :disabled="!importYear||!importMonth"
        style="margin-left: 10px;float:right"
        class="upload-demo"
        :action="this.$http.defaults.baseURL+'api/busPerformance/saveImport?drny='+importYear+'-'+(importMonth<10?('0'+importMonth):importMonth)"
        :on-success="handleUploadSucc"
        :on-error="uploadError"
        :headers="myHeaders"
        :before-upload="beforeUpload"
        :show-file-list="false"
      >
        <el-button
          :disabled="!importYear||!importMonth"
          type="success"
          class="filter-item"
          icon="el-icon-edit"
        >导入</el-button>
      </el-upload>

      <el-select v-if="importYear" v-model="importMonth" placeholder="选月" clearable style="margin-left: 10px;width: 90px;float:right" class="filter-item">
        <el-option v-for="count in 12" :key="count" :label="count+'月'" :value="count" />
      </el-select>
      <el-date-picker
        v-model="importYear"
        align="right"
        unlink-panels
        placeholder="导入年份"
        style="margin-left: 10px;width:120px;float:right"
        class="filter-item"
        type="year"
        value-format="yyyy"
      />
    </div>

    <el-table v-loading="listLoading" :data="list" border fit highlight-current-row style="width: 100%" @sort-change="sortChange" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="50" align="center" />

      <el-table-column prop="bm" label="部门" width="150" sortable="custom" />

      <el-table-column min-width="300px" prop="xm" label="姓名" sortable="custom" show-overflow-tooltip />

      <el-table-column width="100px" prop="drny" align="center" label="月份" sortable="custom" />

      <el-table-column align="center" label="操作" width="300">
        <template slot-scope="scope">
          <el-button size="small" icon="el-icon-search" @click="detail(scope.row.id)">
            查看
          </el-button>
          <el-popconfirm title="确定发送信息吗？" style="margin-left:10px;" @onConfirm="sendMessage(scope.row)">
            <el-button slot="reference" type="primary" size="small" icon="el-icon-s-comment">发消息</el-button>
          </el-popconfirm>
          <el-popconfirm title="确定删除该信息吗？" style="margin-left:10px;" @onConfirm="deleteData(scope.row.uid)">
            <el-button slot="reference" type="danger" size="small" icon="el-icon-delete">删除</el-button>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" />
  </div>
</template>

<script>
// import { fetchList } from '@/api/article'
import Pagination from '@/components/Pagination' // Secondary package based on el-pagination
import Edit from './components/ArticleDetail'

export default {
  name: 'ArticleList',
  components: { Pagination, Edit },
  filters: {
    statusFilter(status) {
      const statusMap = {
        published: 'success',
        draft: 'info',
        deleted: 'danger'
      }
      return statusMap[status]
    }
  },
  data() {
    return {
      myHeaders: {
        Authorization: 'Bearer ' + localStorage.getItem('token')
      },
      importYear: '',
      importMonth: '',
      deptList: [],
      classList: [],
      classForm: {
        parentClass: 14,
        label: ''
      },
      diclist: [],
      settingVisible: false,
      item: {},
      dialogtitle: '新增',
      dialogVisible: false,
      readonly: false,
      timestamp: false,
      list: [],
      total: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        limit: 10,
        year: null,
        month: null,
        sysDeptId: ''
      },
      Sortkey: '',
      Isace: '',
      multipleSelection: [],
      id: ''
    }
  },
  created() {
    this.getDepts()
    this.getList()
  },
  methods: {
    beforeUpload() {
      if (!this.importYear || !this.importMonth) {
        this.$message.error('请先选择导入月份!')
        return false
      } else {
        return new Promise((res, rej) => {
          const messageDate = this.importYear + '年' + this.importMonth + '月'
          let message = '此操作将覆盖 ' + messageDate + ' 数据, 是否继续？'
          let importDate = new Date()
          importDate = new Date(this.importYear + '/' + this.importMonth + '/1')
          if (importDate > new Date()) {
            message = '当前选择的 ' + messageDate + ' 是未来时间，请谨慎选择！是否继续？'
          }
          this.$confirm(message, '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            return res()
          }).catch(() => {
            this.$message({
              type: 'info',
              message: '已取消'
            })
            return rej()
          })
        })
      }
    },
    uploadError(err) {
      console.log(err)
      this.$message({
        message: '导入失败:' + err,
        type: 'error',
        duration: 10000
      })
    },
    handleUploadSucc(response, file, fileList) {
      if (response.success) {
        if (response.result.length === 0) {
          this.$message({
            type: 'success',
            message: '导入成功!'
          })
          this.getList()
        } else {
          let errorMessage = ''
          let index = 0
          for (const item of response.result) {
            console.log(item)
            const errortypetext = item.errortype === 1 ? ' 有误 ' : ' 存在多条记录 '
            const splitText = index === 0 ? '' : ''
            errorMessage = errorMessage + splitText + '行号：' + item.row + ' 员工姓名/邮箱' + errortypetext + '<br>'
            index++
          }
          console.log(index)
          this.$message({
            dangerouslyUseHTMLString: true,
            type: 'error',
            message: '导入错误：<br>' + errorMessage,
            duration: 10000
          })
          this.getList()
        }
      } else {
        this.$message({
          message: '导入失败:' + response.message,
          type: 'error',
          duration: 10000
        })
      }
    },
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    deleteDataByMonth() {
      let mydate = this.importYear
      if (this.importMonth) {
        mydate = mydate + '-' + (this.importMonth < 10 ? '0' + this.importMonth : this.importMonth)
      }
      this.$http
        .get('/api/busPerformance/removeByDate?date=' + mydate)
        .then(response => {
          if (response.data.success === true) {
            this.$message({
              message: '删除成功',
              type: 'success'
            })
            this.getList()
          } else {
            console.log('删除失败:' + response.data.message)
            this.$message({
              message: '删除失败:' + response.data.message,
              type: 'error'
            })
          }
        })
        .catch(error => {
          console.log(error)
        })
    },
    sendMessageByMonth() {
      let mydate = this.importYear
      if (this.importMonth) {
        mydate = mydate + '-' + (this.importMonth < 10 ? '0' + this.importMonth : this.importMonth)
      }
      this.$http
        .post('/api/busPerformance/sendMessage', { date: mydate })
        .then(response => {
          if (response.data.success === true) {
            this.$message({
              message: '发送成功',
              type: 'success'
            })
            this.getList()
          } else {
            console.log('发送失败:' + response.data.message)
            this.$message({
              message: '发送失败:' + response.data.message,
              type: 'error'
            })
          }
        })
        .catch(error => {
          console.log(error)
        })
    },
    deleteData(id) {
      let ids = []
      if (id) {
        ids = [id]
      } else {
        ids = this.multipleSelection.map(item => item.uid)
      }
      if (ids.length > 0) {
        this.$http
          .post('/api/busPerformance/removeByUid', { uidList: ids })
          .then(response => {
            if (response.data.success === true) {
              this.$message({
                message: '删除成功',
                type: 'success'
              })
              this.getList()
            } else {
              console.log('删除失败:' + response.data.message)
              this.$message({
                message: '删除失败:' + response.data.message,
                type: 'error'
              })
            }
          })
          .catch(error => {
            console.log(error)
          })
      } else {
        this.$message({
          message: '请至少选择一条信息',
          type: 'danger'
        })
      }
    },
    sendMessage(data) {
      let list = []
      if (data) {
        list = [{ id: data.id, date: data.drny, userId: data.userId }]
      } else {
        list = this.multipleSelection.map(item => ({ id: item.id, date: item.drny, userId: item.userId }))
      }
      if (list.length > 0) {
        this.$http
          .post('/api/busPerformance/sendMessage', { list: list })
          .then(response => {
            if (response.data.success === true) {
              this.$message({
                message: '发送成功',
                type: 'success'
              })
              this.getList()
            } else {
              console.log('发送失败:' + response.data.message)
              this.$message({
                message: '发送失败:' + response.data.message,
                type: 'error'
              })
            }
          })
          .catch(error => {
            console.log(error)
          })
      } else {
        this.$message({
          message: '请至少选择一条信息',
          type: 'danger'
        })
      }
    },
    sortChange(column, prop, order) {
      this.Sortkey = column.prop
      if (column.order === 'ascending') {
        this.Isace = 'asc'
      } else {
        this.Isace = 'desc'
      }
      this.getList()
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    addnew() {
      this.id = 0
      this.readonly = false
      this.dialogtitle = '新增'
      this.dialogVisible = true
      this.timestamp = new Date().getTime()
    },
    detail(id) {
      this.id = id
      this.readonly = true
      this.dialogtitle = '查看'
      this.dialogVisible = true
      this.timestamp = new Date().getTime()
    },
    dialogHide(flag) {
      this.dialogVisible = false
      this.getList()
    },
    getDepts() {
      const para = {
        pageNum: 1,
        pageSize: 1000
      }
      this.$http
        .post('/api/sysDept/queryPage', para)
        .then(response => {
          if (response.data.success === true) {
            this.deptList = []
            for (const item of response.data.result.records) {
              this.deptList.push({ label: item.deptName, value: item.id })
            }
          } else {
            console.log('获取失败:' + response.data.message)
            this.$message({
              message: '获取失败:' + response.data.message,
              type: 'error'
            })
          }
        })
        .catch(error => {
          console.log(error)
        })
    },
    getList() {
      let beginDate = null
      let endDate = null
      if (this.listQuery.year) {
        if (this.listQuery.month) {
          const mydate = this.listQuery.month < 10 ? this.listQuery.year + '-0' + this.listQuery.month : this.listQuery.year + '-' + this.listQuery.month
          beginDate = mydate
          endDate = mydate
        } else {
          beginDate = this.listQuery.year + '-01'
          endDate = this.listQuery.year + '-12'
        }
      }
      const para = {
        beginDate: beginDate,
        endDate: endDate,
        deptId: this.listQuery.sysDeptId,
        orderField: this.Sortkey,
        orderType: this.Isace,
        pageNum: this.listQuery.page,
        pageSize: this.listQuery.limit
      }
      this.listLoading = true
      this.$http
        .post('/api/busPerformance/queryDeptPerformanceByPage', para)
        .then(response => {
          this.listLoading = false
          if (response.data.success === true) {
            this.list = response.data.result.records
            this.total = response.data.result.total
            if (response.data.result.current > response.data.result.pages && response.data.result.pages !== 0) {
              this.listQuery.page = response.data.result.pages
              this.getList()
            }
          } else {
            console.log('获取失败:' + response.data.message)
            this.$message({
              message: '获取失败:' + response.data.message,
              type: 'error'
            })
          }
        })
        .catch(error => {
          console.log(error)
          this.listLoading = false
        })
      // fetchList(this.listQuery).then(response => {
      //   this.list = response.data.items
      //   this.total = response.data.total
      //   this.listLoading = false
      // })
    }
  }
}
</script>

<style scoped>
.edit-input {
  padding-right: 100px;
}
.cancel-btn {
  position: absolute;
  right: 15px;
  top: 10px;
}
</style>
